/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：太平金科-基础组件封装层-分布式协调工具Zookeeper-缺省实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taipingframework.boot.zookeeper.listener;

import com.taipingframework.utility.context.BeanLifecycle;
import com.taipingframework.utility.context.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.springframework.context.ApplicationContext;

import java.util.Objects;

@Slf4j
public class ZookeeperWatcher extends BeanLifecycle implements Watcher {

    private static ApplicationContext applicationContext;

    @Override
    protected void initMethod() {
        applicationContext = SpringContextHolder.getApplicationContext();
    }

    /**
     * 事件通知
     */
    @Override
    public void process(WatchedEvent event) {
        if (Objects.nonNull(applicationContext)) {
            applicationContext.publishEvent(new ZookeeperEvent(this, event));
        }

        String path = event.getPath(); // 节点路径
        Watcher.Event.KeeperState state = event.getState(); // 事件状态
        Watcher.Event.EventType type = event.getType(); // 事件类型

        if (Watcher.Event.KeeperState.SyncConnected == state) { // 连接成功
            if (Watcher.Event.EventType.None == type) {
                log.debug("zookeeper-event：连接成功 ... ...");
            } else if (Watcher.Event.EventType.NodeCreated == type) {
                log.debug("zookeeper-event：新增节点【{}】", path);
            } else if (Watcher.Event.EventType.NodeDataChanged == type) {
                log.debug("zookeeper-event：修改节点【{}】", path);
            } else if (Watcher.Event.EventType.NodeDeleted == type) {
                log.debug("zookeeper-event：删除节点【{}】", path);
            } else if (Watcher.Event.EventType.NodeChildrenChanged == type) {
                log.debug("zookeeper-event：子节点变更【{}】", path);
            } else {
                log.warn("zookeeper-event：{}", event.toString());
            }
        } else if (Watcher.Event.KeeperState.Disconnected == state) { // 连接失败
            log.error("zookeeper-event：连接失败，Details：{}", event.toString());
        } else if (Watcher.Event.KeeperState.AuthFailed == state) { // 认证失败
            log.error("zookeeper-event：认证失败，Details：{}", event.toString());
        } else if (Watcher.Event.KeeperState.Expired == state) { // 会话过期
            log.error("zookeeper-event：会话过期，Details：{}", event.toString());
        } else {
            log.warn("zookeeper-event：{}", event.toString());
        }
    }

}
